package controllers.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import models.EntityContainer;
import models.ResultPair;
import models.Target;
import controllers.data.providers.Mql;
import controllers.data.providers.Sparql;
import controllers.similarity.EntitySuggestor;


public class RequestController
{

    public static Map<String, String>          urlMap      = new HashMap<>();
    public static Map<String, EntityContainer> instanceMap = new HashMap<>();


    public static String getData(String query, Target t)
    {
        List<EntityContainer> result = new ArrayList<>();
        result.addAll(RequestBuilder.search(query, t));
        return iterableToHTML(result, t.toString());
    }


    public static String loadInstance(String id, Target source)
    {
        EntityContainer instance;
        switch(source) {
            case DBPEDIA:
            case YAGO:
                instance = Sparql.loadInstance(urlMap.get(id), source);
            break;
            case FREEBASE:
                instance = Mql.loadInstance(urlMap.get(id), source);
            break;
            default:
                System.err.println("Not yet implemented provider");
                return "Not yet implemented provider";
        }
        if(instance != null) {
            // System.out.println(instance.toString());
        }

        instanceMap.put(id, instance);

        return id;
    }


    public static String startAI(String id, Target source, Target target)
    {
        EntityContainer instance = instanceMap.get(id);
        // if(instance != null)
        // System.out.println(instance.toString());

        Set<ResultPair> rpList = EntitySuggestor.getSuggestion(instance, source, target);

        if(id != null) {
            return ResultPair.setToHtmlTable(new TreeSet<>(rpList));
        } else {
            return "error";
        }
    }


    public static String iterableToHTML(Collection<EntityContainer> iterable, String source)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("<ul>");
        int z = 0;
        for(EntityContainer entry : new TreeSet<EntityContainer>(iterable).descendingSet()) {
            String id = UUID.randomUUID().toString();
            sb.append("<li title=\"" + entry.getURI() + "\" data-id=\"" + id + "\" data-src=\"" + source + "\" \"><a data-placement=\"right\"  rel=\"tooltip\" title=\"" + entry.getURI() + "\" href=\"#\">" + entry.getLocalName() + "</a></li>");
            urlMap.put(id, entry.getURI());
            if(++z == 10)
                break; // TODO: remove break
        }
        sb.append("</ul>");

        return sb.toString();
    }

}
